package gui.nodes;

import gui.AbstractViewPane;
import gui.CalendrierServiceUI;
import gui.MainController;
import gui.ServiceUIConsulter;
import gui.ServiceUIModifier;
import gui.ServiceUISupprimer;
import gui.AbstractViewPane.ViewMode;

import java.awt.event.*;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

import business.AnneeEtudeBL;
import business.ServiceBL;

import utility.Record;

public class ServiceNode extends AbstractNode {

	int serviceId;
	int seeId;
	String serviceName;
	DefaultMutableTreeNode serviceNode;
	AbstractNode parentNode;

	public ServiceNode(AbstractNode parentNode, Record serviceRec, int see) {
		this.parentNode = parentNode;
		seeId = see;
		this.serviceId = serviceRec.getId();
		this.serviceName = serviceRec.getLibelle();
	}

	@Override
	public JPopupMenu makePopup() {
		return new Popup();
	}

	@Override
	public String getNodeName() {
		return serviceName;
	}

	public void loadPrimaryViewPane() {
		AbstractViewPane newViewPane = new CalendrierServiceUI(serviceId);
		MainController.getInstance().setViewPane(newViewPane);
		}	

	public void loadConsulterViewPane() {
		AbstractViewPane newViewPane = new ServiceUIConsulter(parentNode, ViewMode.CONSULTATION, serviceId, seeId);
		MainController.getInstance().setViewPane(newViewPane);
		}

	public void loadModifierViewPane() {
		AbstractViewPane newViewPane = new ServiceUIConsulter(parentNode, ViewMode.MODIFICATION, serviceId, seeId);
		MainController.getInstance().setViewPane(newViewPane);
		}
	public void loadSupprimerViewPane() {
		if (supprimer() == JOptionPane.YES_OPTION) {
			ServiceBL serviceBL = new ServiceBL(serviceId);
			serviceBL.supprimerService();
		}
		((AbstractNode)parent).refresh();
		}

		private class Popup extends JPopupMenu implements ActionListener {
			JMenuItem consulter = new JMenuItem("Consulter les informations");
			JMenuItem modifier = new JMenuItem("Modifier");
			JMenuItem supprimer = new JMenuItem("Supprimer");

			public Popup() {
				consulter.addActionListener(this);
				modifier.addActionListener(this);
				supprimer.addActionListener(this);
				add(consulter);
				add(modifier);
				add(supprimer);
			}

			public void actionPerformed(ActionEvent e) {
				if (e.getSource() == consulter) {
					loadConsulterViewPane();
				}
				if (e.getSource() == modifier) {
					loadModifierViewPane();
				}
				if (e.getSource() == supprimer) {
					loadSupprimerViewPane();
				}

			}

		}

		@Override
		public void expandHook() {
			this.removeAllChildren();
			
		}

		public int supprimer() {
			return JOptionPane.showConfirmDialog(
				    null,
				    "Êtes vous sûr de vouloir supprimer le service\n"+
				    //ensBL.getName()+" "+ensBL.getPrenom()+
				    " ?",
				    "Avertissement",
				    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			
		}


}
